// ignore_for_file: public_member_api_docs, sort_constructors_first
import 'package:flutter/material.dart';

import 'package:lib_uikit/lib_uikit.dart';

enum GTPaginationV3Style {
  /// 不显示页码
  invisiblePagination,

  /// 显示页码
  visiblePagination,
}

class GTPaginationV3 extends StatefulWidget {
  const GTPaginationV3({
    Key? key,
    this.initPage = 1,
    required this.totalPage,
    required this.style,
    required this.onPageChange,
  }) : super(key: key);

  /// 初始化页,默认从1开始
  final int initPage;

  /// 总页数
  final int totalPage;

  /// 翻页器样式
  final GTPaginationV3Style style;

  /// 翻页回调
  final void Function(int page) onPageChange;

  @override
  State<GTPaginationV3> createState() => _GTPaginationV3State();
}

class _GTPaginationV3State extends State<GTPaginationV3> {
  /// 当前页
  int _currentPage = 1;

  /// 总页数
  int get _totalPage => widget.totalPage;

  @override
  void initState() {
    super.initState();
    _currentPage = widget.initPage;
    assert(_currentPage > 0, '初始页不能小于1');
    assert(_totalPage > 0, '总页数不能小于1');
  }

  @override
  Widget build(BuildContext context) {
    switch (widget.style) {
      case GTPaginationV3Style.invisiblePagination:
        return _InvisiblePagination(
          currentPage: _currentPage,
          totalPage: _totalPage,
          onPageChange: _onPageChange,
        );
      case GTPaginationV3Style.visiblePagination:
        return _VisiblePagination(
          currentPage: _currentPage,
          totalPage: _totalPage,
          onPageChange: _onPageChange,
        );
      default:
        return Container();
    }
  }

  /// 页码改变
  void _onPageChange(int page) {
    if (page < 1 || page > _totalPage || page == _currentPage) {
      return;
    }
    setState(() {
      _currentPage = page;
    });
    widget.onPageChange(page);
  }
}

class _InvisiblePagination extends StatelessWidget {
  const _InvisiblePagination({
    required this.currentPage,
    required this.totalPage,
    required this.onPageChange,
  });

  /// 当前页
  final int currentPage;

  /// 总页数
  final int totalPage;

  /// 翻页回调
  final void Function(int page) onPageChange;

  @override
  Widget build(BuildContext context) {
    final bool canLeft = currentPage > 1 && currentPage <= totalPage;
    final bool canRight = currentPage < totalPage && currentPage >= 1;
    final Color leftIconColor = canLeft ? GTColorsV3.icon1.color : GTColorsV3.icon7.color;
    final Color rightIconColor = canRight ? GTColorsV3.icon1.color : GTColorsV3.icon7.color;
    return SizedBox(
      width: 104,
      height: 24,
      child: Row(
        children: [
          GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () => onPageChange(currentPage - 1),
            child: Container(
              width: 44,
              height: 24,
              decoration: BoxDecoration(
                color: GTColorsV3.neutral5.color,
                borderRadius: BorderRadius.circular(4),
              ),
              child: Icon(GTIconFont.e8c7, size: 12, color: leftIconColor),
            ),
          ),
          const Spacer(),
          GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () => onPageChange(currentPage + 1),
            child: Container(
              width: 44,
              height: 24,
              decoration: BoxDecoration(
                color: GTColorsV3.neutral5.color,
                borderRadius: BorderRadius.circular(4),
              ),
              child: Icon(GTIconFont.e8b6, size: 12, color: rightIconColor),
            ),
          ),
        ],
      ),
    );
  }
}

class _VisiblePagination extends StatelessWidget {
  const _VisiblePagination({
    required this.currentPage,
    required this.totalPage,
    required this.onPageChange,
  });

  /// 当前页
  final int currentPage;

  /// 总页数
  final int totalPage;

  /// 翻页回调
  final void Function(int page) onPageChange;

  static const double _itemSpace = 4.0;

  @override
  Widget build(BuildContext context) {
    return totalPage > 4 ? _buildArrowLine() : _buildNumLine();
  }

  /// 带箭头
  Widget _buildArrowLine() {
    final bool canLeft = currentPage > 1 && currentPage <= totalPage;
    final bool canRight = currentPage < totalPage && currentPage >= 1;
    final Color leftIconColor = canLeft ? GTColorsV3.icon1.color : GTColorsV3.icon7.color;
    final Color rightIconColor = canRight ? GTColorsV3.icon1.color : GTColorsV3.icon7.color;

    List<String> pages = [];
    for (var i = -2; i < 3; i++) {
      int tPage = currentPage + i;
      if (tPage > 0 && tPage < totalPage) {
        pages.add(tPage.toString());
      }
    }
    if ((int.tryParse(pages.first) ?? 0) > 1) {
      pages.insert(0, '...');
    }
    if ((int.tryParse(pages.last) ?? 0) < totalPage - 1) {
      pages.add('...');
    }
    pages.add(totalPage.toString());
    return Wrap(
      spacing: _itemSpace,
      children: [
        GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: () => onPageChange(currentPage - 1),
          child: Container(
            width: 28,
            height: 28,
            alignment: Alignment.center,
            child: Icon(GTIconFont.e8f6, size: 16, color: leftIconColor),
          ),
        ),
        ...pages.map((e) => _buildNumItem(e)).toList(),
        GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: () => onPageChange(currentPage + 1),
          child: Container(
            height: 28,
            width: 28,
            alignment: Alignment.center,
            child: Icon(GTIconFont.e8f7, size: 16, color: rightIconColor),
          ),
        ),
      ],
    );
  }

  /// 纯数字
  Widget _buildNumLine() {
    List<String> pages = List.generate(totalPage, (index) => (index + 1).toString()).toList();
    return Wrap(
      spacing: _itemSpace,
      children: pages.map((e) => _buildNumItem(e)).toList(),
    );
  }

  Widget _buildNumItem(String text) {
    /// 0则为...
    final page = (int.tryParse(text) ?? 0);
    bool isSelected = page == currentPage;
    return GestureDetector(
      onTap: () {
        if (page < 1) {
          return;
        }
        onPageChange(page);
      },
      behavior: HitTestBehavior.opaque,
      child: Container(
        width: 28,
        height: 28,
        alignment: Alignment.center,
        decoration:
            isSelected ? BoxDecoration(color: GTColorsV3.neutral3.color, borderRadius: BorderRadius.circular(4)) : null,
        child: Text(
          text,
          style: TextStyle(
            fontSize: 14,
            fontFamily: 'GTFontFamily',
            fontWeight: FontWeight.w500,
            color: GTColorsV3.uikitText1V3.color,
          ),
        ),
      ),
    );
  }
}
